package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 石小俊
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        // 获取解析工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 获取解析器
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            // 解析请求
            List<FileItem> fileItems = upload.parseRequest(request);
            Map<String, FileItem> items = new HashMap<>();
            for (FileItem item : fileItems) {
                items.put(item.getFieldName(), item);
            }

            FileItem file = items.get("file");
            String fileName = file.getName();
            // 限制不允许上传jsp文件
            if (fileName.endsWith(".jsp")) {
                request.setAttribute("uploadMsg", "不允许上传jsp文件");
                request.getRequestDispatcher("/jsp/upload.jsp").forward(request, response);
                return;
            }


            ServletContext application = getServletContext();
            String path = application.getRealPath("/upload/" + new SimpleDateFormat("yyyyMMdd").format(new Date()));
            System.out.println("path:" + path);
            File f = new File(path);
            f.mkdirs();
            file.write(new File(path, fileName));
            out.println("<span style='color:green;'>恭喜您,上传成功</span>");
        } catch (FileUploadException e) {
            e.printStackTrace();
            out.println("<span style='color:red;'>对不起,上传失败</span>");
        } catch (Exception e) {
            e.printStackTrace();
            out.println("<span style='color:red;'>对不起,上传失败</span>");
        }
    }
}
